#!/bin/bash
#Bazzite 外置硬盘自动挂载工具 (基于 scawp 的 Steam Deck 脚本修改)
#许可证: DBAD: https://github.com/scawp/Steam-Deck.Mount-External-Drive/blob/main/LICENSE.md
#源代码: https://github.com/scawp/Steam-Deck.Mount-External-Drive
#使用风险自负！

#使用以下命令一键安装:
#curl -sSL https://raw.githubusercontent.com/scawp/Steam-Deck.Mount-External-Drive/main/curl_install.sh | bash

#设置任何错误立即退出脚本
set -e

repo_url="https://raw.githubusercontent.com/scawp/Steam-Deck.Mount-External-Drive/main"
repo_lib_dir="$repo_url/lib"

tmp_dir="/tmp/scawp.SDMED.install"

rules_install_dir="/etc/udev/rules.d"
service_install_dir="/etc/systemd/system"
script_install_dir="/var/home/deck/.local/share/scawp/SDMED"

device_name="$(uname --nodename)"
user="$(id -u deck)"

# 检查是否运行在 Bazzite 系统上
if ! grep -q "bazzite" /etc/os-release; then
  zenity --question --width=400 \
  --title="系统检查" \
  --text="本脚本专为 Bazzite 系统设计 \
  \n检测到您正在使用其他系统 \
  \n是否确定要继续安装？"
  if [ "$?" != 0 ]; then
    echo "安装已取消。"
    exit 1;
  fi
fi

function install_automount () {
  zenity --question --width=400 \
    --title="自动挂载服务安装" \
    --text="安装前请确认已阅读 $repo_url/README.md \
  \n是否要安装外置硬盘自动挂载服务？"
  if [ "$?" != 0 ]; then
    echo "安装已取消。"
    exit 0;
  fi

  echo "正在创建临时目录 $tmp_dir"
  mkdir -p "$tmp_dir"

  echo "正在下载必要文件..."
  curl -o "$tmp_dir/automount.sh" "$repo_url/automount.sh"
  curl -o "$tmp_dir/external-drive-mount@.service" "$repo_lib_dir/external-drive-mount@.service"
  curl -o "$tmp_dir/99-steamos-automount.rules" "$repo_lib_dir/99-steamos-automount.rules"

  # 为 Bazzite 修改 automount.sh 中的路径
  sed -i 's|/home/deck|/var/home/deck|g' "$tmp_dir/automount.sh"

  echo "正在创建脚本目录 $script_install_dir"
  mkdir -p "$script_install_dir"

  echo "正在复制 $tmp_dir/automount.sh 到 $script_install_dir/automount.sh"
  sudo cp "$tmp_dir/automount.sh" "$script_install_dir/automount.sh"

  echo "正在设置执行权限并移除写权限"
  sudo chmod 555 "$script_install_dir/automount.sh"

  echo "正在复制 udev 规则文件到 $rules_install_dir"
  sudo cp "$tmp_dir/99-steamos-automount.rules" "$rules_install_dir/99-steamos-automount.rules"

  # 移除旧版规则文件（如果存在）
  if [ -f "$rules_install_dir/99-external-drive-mount.rules" ]; then
    sudo rm "$rules_install_dir/99-external-drive-mount.rules"
  fi

  if [ -f "$rules_install_dir/98-external-drive-mount.rules" ]; then
    sudo rm "$rules_install_dir/98-external-drive-mount.rules"
  fi

  echo "正在复制 systemd 服务文件到 $service_install_dir"
  sudo cp "$tmp_dir/external-drive-mount@.service" "$service_install_dir/external-drive-mount@.service"

  echo "正在重新加载服务..."
  sudo udevadm control --reload
  sudo systemctl daemon-reload

  zenity --info --width=400 \
    --title="安装成功" \
    --text="外置硬盘自动挂载服务已成功安装！"
}

install_automount

zenity --question --width=400 \
  --title="重启提示" \
  --text="需要重启系统才能使更改生效 \
  \n是否立即重启？"
if [ "$?" != 0 ]; then
  zenity --info --width=400 \
    --title="安装完成" \
    --text="安装已完成！请稍后手动重启系统使更改生效。"
  exit 0;
fi

reboot

echo "安装过程完成。"
